<!DOCTYPE html>
<html>

<head>
  <title>
    Test CPU performance of the WebGLRenderingContext.drawArrays binding
  </title>
  <script src="../resources/runner.js"></script>
</head>

<body>
  <canvas id="canvas" width=400 height=400></canvas>
  <script>
    const canvas = document.getElementById('canvas');
    const gl = canvas.getContext('webgl');

    const vertexBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
      0.0, 0.5, 0.0,
      -0.5, -0.5, 0.0,
      0.5, -0.5, 0.0,
    ]), gl.STATIC_DRAW);
    gl.bindBuffer(gl.ARRAY_BUFFER, null);

    const vertShader = gl.createShader(gl.VERTEX_SHADER);
    gl.shaderSource(vertShader, `
      attribute vec3 a_coord;
      void main() {
          gl_Position = vec4(a_coord, 1.0);
      }`);
    gl.compileShader(vertShader);

    const fragShader = gl.createShader(gl.FRAGMENT_SHADER);
    gl.shaderSource(fragShader, `
      precision mediump float;
      uniform vec3 u_color;
      void main() {
          gl_FragColor = vec4(u_color, 1.0);
      }`);
    gl.compileShader(fragShader);

    const shaderProgram = gl.createProgram();
    gl.attachShader(shaderProgram, vertShader);
    gl.attachShader(shaderProgram, fragShader);
    gl.linkProgram(shaderProgram);

    gl.useProgram(shaderProgram);
    const aCoord = gl.getAttribLocation(shaderProgram, 'a_coord');
    const uColor = gl.getUniformLocation(shaderProgram, 'u_color');

    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

    gl.vertexAttribPointer(aCoord, 3, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(aCoord);

    gl.clearColor(0, 0, 0, 1);
    gl.viewport(0, 0, canvas.width, canvas.height);
    gl.uniform3fv(uColor, [0, 1, 0]);

    const iterations = 10000;
    PerfTestRunner.measureInnerRAFTime({
      description: `CPU time for ${iterations} calls to WebGLRenderingContext.drawArrays`,
      warmUpCount: 10,
      run() {
        gl.clear(gl.COLOR_BUFFER_BIT);
        for (let i = 0; i < iterations; ++i) {
          gl.drawArrays(gl.TRIANGLES, 0, 3);
        }
      }
    });
  </script>
</body>

</html>
